import logging
import random
import time
import json
import math
import inspect
import os
import sys

logger = logging.getLogger(__name__)

CURRENTDIR = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
PARENTDIR = os.path.dirname(CURRENTDIR)
sys.path.insert(0, CURRENTDIR)
sys.path.insert(0, PARENTDIR)

from web.common.fpval import safarifpval, chromefpval, firefoxfpval
from web.common.informlib import get_siteinform


class CookieGen(object):
    def __init__(self):
        self.fpval = ""
        self.informinfo = ""

    def _sign(self, cs, api):
        temp_string = ""
        cs_length = len(cs)
        api_length = len(api)

        if api_length > 0:
            for index in range(0, cs_length):
                temp_char = cs[index]
                temp_code = ord(temp_char)
                temp_code_2 = ord(api[index % api_length])
                new_code = self._get_code(temp_code, 47, 57, temp_code_2)
                new_char = ""
                if new_code != cs[index]:
                    new_char = chr(new_code)
                    try:
                        temp_string += new_char
                    except BaseException:
                        logging.error("Unprintable character => %s" % new_char)

        else:
            logging.error("Signature cannot be blank")
        logging.info("Result signature: %s" % temp_string[0:16])

        return temp_string[0:16]

    def _get_code(self, char_code, const_1, const_2, char_result):
        if const_1 < char_code <= const_2:
            char_code += char_result % (const_2 - const_1)
            if char_code > const_2:
                char_code = char_code - const_2 + const_1

        return char_code

    def get_sensor_data(self, cookie, url, useragent=None):
        if useragent is None:
            USER_AGENT = (
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) "
                "Version/12.1.1 Safari/605.1.15"
            )
        else:
            USER_AGENT = str(useragent)
        if "Chrome" in USER_AGENT:
            fpval = chromefpval()
            REQUEST_INFO = "12147"
            PRODUCT_SUB = "20030107"
        elif "Safari" in USER_AGENT:
            fpval = safarifpval()
            REQUEST_INFO = "11011"
            PRODUCT_SUB = "20030107"
        else:
            fpval = firefoxfpval()
            REQUEST_INFO = "11059"
            PRODUCT_SUB = "20100101"
        INFORM_INFO = get_siteinform(url)
        FORM_INFO = get_siteinform(url)
        WIDTH = str(random.randint(1200, 1920))
        HEIGHT = str(random.randint(768, 1040))
        CS_KEY = "0a46G5m17Vrp4o4c"
        API_KEY = "afSbep8yjnZUjq3aL010jO15Sawj2VZfdYK8uY90uxq"
        VERSION = "1.43"
        LANGUAGE = "en-US"
        ENGINE = "Gecko"
        PLUGIN_COUNT = str(random.randint(1, 4))
        HEADLESS = "0"
        NEW_WINDOW = "0"
        SPAM_BOT = "0"
        AVAIL_WIDTH = "1920"
        AVAIL_HEIGHT = "1040"
        SCREEN_WIDTH = "1920"
        SCREEN_HEIGHT = "1080"
        WINDOW_WIDTH = WIDTH
        WINDOW_HEIGHT = HEIGHT
        WINDOW_OWIDTH = "1920"
        IS_IE = "0"
        DOC_MODE = "0"
        CHROME_WEB_STORE = "0"
        ON_LINE = "1"
        OPERA = "0"
        FIREFOX = "0"
        SAFARI = "0"
        RTC_SUPPORT = "1"
        WINDOW_TOP = "0"
        VIBRATION = "0"
        BATTERY = "0"
        FOR_EACH = "0"
        FILE_READER = "1"
        ORIENTATION = "do_dis"
        MOTION = "dm_dis"
        TOUCH = "t_dis"
        K_ACT = ""
        M_ACT = ""
        T_ACT = ""
        DO_ACT = ""
        DM_ACT = ""
        P_ACT = ""
        VC_ACT = ""
        MN_R = ""
        FP_VALUE = fpval + ";dis;,3;true;true;true;420;true;24;24;true;true;-1"

        url = url

        signature = self._sign(CS_KEY, API_KEY)
        date_floor = int(math.floor(int(time.time_ns() // 1000000) / 36e5))
        signature += self._sign(str(date_floor), signature)

        timestamp = int(time.time_ns() // 1000000)
        time_calc = int(timestamp / (2016 * 2016))
        time_calc2 = int(timestamp % 1e7)
        time_calc3 = int(time_calc / 23)
        time_calc4 = int(time_calc3 / 6)
        sleeptime = random.uniform(0.01, 0.03)
        time.sleep(sleeptime)
        time_elapsed = str(int(time.time_ns() // 1000000) - timestamp)
        time.sleep(0.03 - sleeptime)
        time_calc5 = int(time.time_ns() // 1000000) - timestamp

        sensor_string = (
            VERSION
            + "-1,2,-94,-100,"
            + USER_AGENT
            + ",uaend,"
            + REQUEST_INFO
            + ","
            + PRODUCT_SUB
            + ","
            + LANGUAGE
            + ","
            + ENGINE
            + ","
            + PLUGIN_COUNT
            + ","
            + HEADLESS
            + ","
            + NEW_WINDOW
            + ","
            + SPAM_BOT
            + ","
            + str(time_calc)
            + ","
            + str(time_calc2)
            + ","
            + AVAIL_WIDTH
            + ","
            + AVAIL_HEIGHT
            + ","
            + SCREEN_WIDTH
            + ","
            + SCREEN_HEIGHT
            + ","
            + WINDOW_WIDTH
            + ","
            + WINDOW_HEIGHT
            + ","
            + WINDOW_OWIDTH
            + ",,cpen:"
            + HEADLESS
            + ",i1:"
            + IS_IE
            + ",dm:"
            + DOC_MODE
            + ",cwen:"
            + CHROME_WEB_STORE
            + ",non:"
            + ON_LINE
            + ",opc:"
            + OPERA
            + ",fc:"
            + FIREFOX
            + ",sc:"
            + SAFARI
            + ",wrc:"
            + RTC_SUPPORT
            + ",isc:"
            + WINDOW_TOP
            + ",vib:"
            + VIBRATION
            + ",bat:"
            + BATTERY
            + ",x11:"
            + FOR_EACH
            + ",x12:"
            + FILE_READER
            + ","
            + str(self._txt_func(USER_AGENT))
            + ","
            + str(random.random())[0:13]
            + ","
            + str(timestamp / 2)
            + ",loc:"
            + "-1,2,-94,-101"
            + ","
            + ORIENTATION
            + ","
            + MOTION
            + ","
            + TOUCH
            + "-1,2,-94,-105,"
            + INFORM_INFO
            + "-1,2,-94,-102,"
            + FORM_INFO
            + "-1,2,-94,-108,"
            + K_ACT
            + "-1,2,-94,-110,"
            + M_ACT
            + "-1,2,-94,-117,"
            + T_ACT
            + "-1,2,-94,-111,"
            + DO_ACT
            + "-1,2,-94,-109,"
            + DM_ACT
            + "-1,2,-94,-114,"
            + P_ACT
            + "-1,2,-94,-103,"
            + VC_ACT
            + "-1,2,-94,-112,"
            + url
            + "-1,2,-94,-115,1,1,0,0,0,0,0,"
            + str(int(time.time_ns() // 1000000) - timestamp)
            + ",0,"
            + str(timestamp)
            + ","
            + time_elapsed
            + ","
            + str(time_calc3)
            + ",0,0,"
            + str(time_calc4)
            + ",0,0,"
            + str(time_calc5)
            + ",0,0,"
            + cookie
            + ","
            + str(self._txt_func(cookie))
            + ",-1,-1,"
            + "26018161"
            + "-1,2,-94,-106,"
            + "0"
            + ","
            + "0"
            + "-1,2,-94,-119,-1-1,2,-94,-122,0,0,0,0,1,0,0-1,2,-94,-123,"
            + MN_R
            + "-1,2,-94,-124,"
        )

        txt_val = self._txt_func(sensor_string)

        sensor_string += (
            "-1,2,-94,-70,"
            + FP_VALUE
            + "-1,2,-94,-80,"
            + str(self._txt_func(FP_VALUE))
            + "-1,2,-94,-116,"
            + str(self._time_func(time_calc2))
            + "-1,2,-94,-118,"
            + str(txt_val)
            + "-1,2,-94,-121,"
        )

        sensor_string = (
            signature
            + sensor_string
            + ";"
            + str(int(time.time() * 1000) - timestamp)
            + ";-1;0"
        )

        sensor_string = '{"sensor_data":"' + sensor_string + '"}'
        logger.debug(sensor_string)

        return sensor_string

    def _txt_func(self, agent):
        result = -1
        if agent != "":
            try:
                temp_result = 0
                for index in range(0, len(agent)):
                    temp_code = ord(agent[index])
                    if temp_code < 128:
                        temp_result += temp_code
                result = temp_result
            except BaseException:
                result = -1

        return str(result)

    def _time_func(self, timestamp):
        temp_val = timestamp
        for index in range(0, 5):
            temp_val2 = int(temp_val / math.pow(10, index)) % 10
            temp_val3 = temp_val2 + 1
            operator = self._get_operator(temp_val3)
            if operator == "+":
                temp_val += temp_val3
            elif operator == "-":
                temp_val -= temp_val3
            elif operator == "*":
                temp_val *= temp_val3
            elif operator == "/":
                temp_val /= temp_val3

        return temp_val

    def _get_operator(self, temp_val):
        temp_result = temp_val % 4
        if temp_result == 2:
            temp_result = 3
        result = temp_result + 42

        return str(result)


safarircfp = {"chrome": "1359025438", "firefox": "1241107008", "safari": "-187826246"}
